#pragma once

#include <iostream>
#include <functional>
#include <cstring>
#include <cassert>
#include <pthread.h>
#include <string>
// header only 开源代码

class Thread;

class Context
{
public:
    Thread *this_;
    void *args_;
public:
    Context() :this_(nullptr), args_(nullptr)
    {}
    ~Context()
    {}
};

class Thread
{
public:
    // using fun_t = std::function<void*(void*)>;
    typedef std::function<void*(void*)> func_t;
    const int num = 1024;
public:
    Thread(func_t func, void *args, int number): func_(func), args_(args)
    {
        // name_ = "thread-";
        // name_ += std::to_string(number);

        char buffer[num];
        snprintf(buffer, sizeof buffer, "thread-%d", number);
        name_ = buffer;

        //start()
        Context *ctx = new Context;
        ctx->args_ = args_;
        ctx->this_ = this;
        int n = pthread_create(&tid_, nullptr, start_routine, ctx);
        assert(n == 0);
        (void)n;
    }

    static void *start_routine(void *args)
    {
        Context *ctx = static_cast<Context*>(args);
        void *ret = ctx->this_->run(ctx->args_);
        delete ctx;
        return ret;
    }

    // void start()
    // {

    // }

    void join()
    {
        int n = pthread_join(tid_, nullptr);
        assert(n == 0);
        (void)n;
    }

    void *run(void *args)
    {
        return func_(args);
    }

    ~Thread()
    {
        //do nothing
    }
private:
    std::string name_;
    pthread_t tid_;
    func_t func_;
    void *args_;
};